using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

namespace Voodoo.Meta.RVModules
{
	public class ChestRoomView : MonoBehaviour
	{
		private Chest currentChest;

		[Space]
		public ChestArea chestArea;

		public KeyArea keyArea;

		public BestRewardArea bestRewardArea;

		public AudioClip chestOpenSound;

		public int keysMax;

		public int chestsMax;

		private bool _lastChestHasOpened;

		private CancellationTokenSource _cancellationTokenSource;

		public Transform Root => currentChest.transform;

		public void FillUpKeys()
		{
			keyArea.SetKeys(keysMax);
		}

		public void UseAKey(Chest chest)
		{
			if (keyArea.UseAKey())
			{
				chest.OpenChest();
			}
		}

		public void OpenChest(Chest chest)
		{
			currentChest = chest;
			chest.SetUpRewardVisual(ChestRoomAdapter.Instance.NextReward());
			PlayCollect();
		}

		public void OnOpen()
		{
			_lastChestHasOpened = false;
			chestArea.FillGrid(chestsMax, this);
			bestRewardArea.SetUp(ChestRoomAdapter.Instance.BestReward.sprite, Color.white);
			FillUpKeys();
		}

		public async Task OnChestOpened()
		{
			if (chestArea.IsChestAvailable())
			{
				if (!keyArea.IsAKeyAvailable())
				{
					ChestRoomAdapter.Instance.ShowButtons();
				}
			}
			else if (!_lastChestHasOpened)
			{
				_lastChestHasOpened = true;
				_cancellationTokenSource = new CancellationTokenSource();
				await Task.Delay(TimeSpan.FromSeconds(1.0), _cancellationTokenSource.Token);
				chestArea.Clean();
				ChestRoomAdapter.Instance.Hide();
			}
		}

		protected void PlayCollect()
		{
			ChestRoomAdapter.DoVibrateMedium();
			ChestRoomAdapter.Instance.CollectReward();
			ChestRoomAdapter.PlaySound(chestOpenSound);
		}

		protected void OnDestroy()
		{
			_cancellationTokenSource?.Cancel();
			if (chestArea != null)
			{
				chestArea.Clean();
				chestArea = null;
			}
			if (keyArea != null)
			{
				keyArea.Dispose();
				keyArea = null;
			}
			if (bestRewardArea != null)
			{
				bestRewardArea.image = null;
				bestRewardArea = null;
			}
		}
	}
}
